package com.ruoyi.project.system.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SiyuCharge;
import com.ruoyi.project.system.domain.SiyuProduct;
import com.ruoyi.project.system.domain.SiyuQuery;
import com.ruoyi.project.system.domain.dto.*;
import com.ruoyi.project.system.mapper.*;
import com.ruoyi.project.system.service.ISiyuQueryService;
import com.ruoyi.project.system.service.ISysPhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/frontPhone")
public class FrontPhoneInfoController extends BaseController {

    @Autowired
    private ISysPhoneService iSysPhoneService;

    @Autowired
    private SysPhoneMapper spm;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SiyuChargeMapper siyuChargeMapper;

    @Autowired
    private SiyuProductMapper siyuProductMapper;

    @Autowired
    private SiyuQueryMapper siyuQueryMapper;

    @GetMapping("/fee")
    public AjaxResult fee(Integer productId, Integer queryId) {
        Long userId = SecurityUtils.getUserId();
        BigDecimal balance = sysUserMapper.selectUserById(userId.longValue()).getBalance();
        SiyuProduct product = siyuProductMapper.selectSiyuProductById(productId);
        if (balance.compareTo(product.getUnitPrice()) < 0) {
            return AjaxResult.warn("余额不足！请联系充值。");
        }
        // 写入扣费记录
        siyuChargeMapper.insertSiyuCharge(new SiyuCharge(
                userId.intValue(),
                queryId,
                balance,
                product.getUnitPrice(),
                balance.subtract(product.getUnitPrice()),
                product.getName()
        ));
        // 减余额
        return toAjax(sysUserMapper.subtractBalance(userId.longValue(), product.getUnitPrice()));
    }

    @GetMapping("/appList")
    public Object appList(@NotBlank AppAuth appAuth) {
        int result = siyuChargeMapper.chargeResult(appAuth.getQueryId(), "APP认证");
        if (result <= 0) {
            return success("未支付");
        }
        Long userId = SecurityUtils.getUserId();
        if (userId != 1l) {
            SiyuQuery siyuQuery = siyuQueryMapper.selectSiyuQueryByQueryId(appAuth.getQueryId());
            if (siyuQuery.getUserId() != userId.intValue()) {
                return error();
            }
        }
        startPage();
        List<AppAuth> list = spm.appList(appAuth);
        return getDataTable(list);
    }

    @GetMapping("/textMessageList")
    public Object textMessageList(@NotBlank TextMessage textMessage) {
        int result = siyuChargeMapper.chargeResult(textMessage.getQueryId(), "社交认证");
        if (result <= 0) {
            return success("未支付");
        }
        Long userId = SecurityUtils.getUserId();
        if (userId != 1l) {
            SiyuQuery siyuQuery = siyuQueryMapper.selectSiyuQueryByQueryId(textMessage.getQueryId());
            if (siyuQuery.getUserId() != userId.intValue()) {
                return error();
            }
        }
        startPage();
        List<TextMessage> list = spm.textMessageList(textMessage);

        if (StringUtils.isNotEmpty(textMessage.getName())){
            for (TextMessage ab : list) {
                if (!textMessage.getName().equals(ab.getName())) {
                    list.remove(ab);
                }
            }
        }
        return getDataTable(iSysPhoneService.disTextMessage(list, textMessage));
    }

    @GetMapping("/addressBookList")
    public Object addressBookList(@NotBlank AddressBook addressBook) {
        int result = siyuChargeMapper.chargeResult(addressBook.getQueryId(), "通讯录认证");
        if (result <= 0) {
            return success("未支付");
        }
        Long userId = SecurityUtils.getUserId();
        if (userId != 1l) {
            SiyuQuery siyuQuery = siyuQueryMapper.selectSiyuQueryByQueryId(addressBook.getQueryId());
            if (siyuQuery.getUserId() != userId.intValue()) {
                return error();
            }
        }
        startPage();
        List<AddressBook> list = spm.addressBookList(addressBook);

        for (AddressBook ad : list) {
            List<Phone> phones = JSONArray.parseArray(ad.getPhones_(), Phone.class);
            if (StringUtils.isNotEmpty(addressBook.getPhones_())) {
                for (int i = 0; i < phones.size(); i++) {
                    if (!phones.get(i).getValue().contains(addressBook.getPhones_())) {
                        phones.remove(i);
                    }
                }
            }
            ad.setPhones(phones);
            ad.setPhones_("");
        }
        return getDataTable(list);
    }

    @GetMapping("/callLogList")
    public AjaxResult callLogList(@NotBlank CallLog callLog) {
        int result = siyuChargeMapper.chargeResult(callLog.getQueryId(), "社交认证");
        if (result <= 0) {
            return success("未支付");
        }
        Long userId = SecurityUtils.getUserId();
        if (userId != 1l) {
            SiyuQuery siyuQuery = siyuQueryMapper.selectSiyuQueryByQueryId(callLog.getQueryId());
            if (siyuQuery.getUserId() != userId.intValue()) {
                return error();
            }
        }
        List<CallLog> list = spm.callLogList(callLog);
        if (list == null || list.isEmpty()) {
            warn("暂无");
        }
        return success(iSysPhoneService.disCallLog(list, callLog));
    }

    @GetMapping("/baseInfo")
    public AjaxResult baseInfo(Integer queryId) {
        int result = siyuChargeMapper.chargeResult(queryId, "基础信息");
        if (result <= 0) {
            return success("未支付");
        }
        Long userId = SecurityUtils.getUserId();
        if (userId != 1l) {
            SiyuQuery siyuQuery = siyuQueryMapper.selectSiyuQueryByQueryId(queryId);
            if (siyuQuery.getUserId() != userId.intValue()) {
                return error();
            }
        }
        Map<String, Object> info = spm.baseInfo(queryId);

        List<Contacts> cons = null;
        if (info != null && !info.isEmpty() && info.containsKey("baseInfo")) {
            String baseInfo = info.get("baseInfo").toString();
            JSONArray lxr = JSON.parseObject(baseInfo).getJSONObject("data").getJSONArray("lxr");

            List<String> lxfs = new ArrayList<>();
            if (StringUtils.isNotEmpty(lxr.getJSONObject(0).getString("lxfs"))) {
                lxfs.add(lxr.getJSONObject(0).getString("lxfs"));
            }
            if (StringUtils.isNotEmpty(lxr.getJSONObject(1).getString("lxfs"))) {
                lxfs.add(lxr.getJSONObject(1).getString("lxfs"));
            }
            if (StringUtils.isNotEmpty(lxr.getJSONObject(2).getString("lxfs"))) {
                lxfs.add(lxr.getJSONObject(2).getString("lxfs"));
            }
            if (!lxfs.isEmpty()) {
                List<CallLog> callLogs = spm.baseInfocallLogList(lxfs, queryId);
                List<CallLogResult> callLogResults = iSysPhoneService.disCallLog(callLogs, new CallLog(queryId));
                cons = iSysPhoneService.disContacts(callLogResults, lxr);
            }
        }
        info.put("cons", cons);
        return success(info);
    }

    @GetMapping("/threeEleInfo")
    public AjaxResult threeEleInfo(Integer queryId) {
        Long userId = SecurityUtils.getUserId();
        BigDecimal balance = sysUserMapper.selectUserById(userId.longValue()).getBalance();
        BigDecimal fee = new BigDecimal(1.f);
        if (balance.compareTo(fee) < 0) {
            return AjaxResult.warn("余额不足！请联系充值。");
        }
        // 写入扣费记录
        siyuChargeMapper.insertSiyuCharge(new SiyuCharge(
                userId.intValue(),
                queryId,
                balance,
                fee,
                balance.subtract(fee),
                "三要素核验"
        ));
        // 减余额
        sysUserMapper.subtractBalance(userId.longValue(), fee);

        SiyuQuery siyuQuery = SpringUtils.getBean(ISiyuQueryService.class).selectSiyuQueryByQueryId(queryId);

        String baseReqSn = "RYC" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase();
        JSONObject params = new JSONObject();
        params.put("req_time", System.currentTimeMillis());
        // 手机三要素
        params.put("request_sn", baseReqSn + "JF007");
        params.put("inter_id", "JF007");
        params.put("name", siyuQuery.getName());
        params.put("cardNo", siyuQuery.getCardNo());
        params.put("mobile", siyuQuery.getTel());
        String sjsys = HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json");

        if (StringUtils.isNotEmpty(sjsys) && sjsys.contains("retdata")) {
            JSONObject object = JSON.parseObject(sjsys);
            spm.setThreeEleAuth(queryId, object.getJSONObject("retdata").toJSONString());
            return success(object.getJSONObject("retdata"));
        } else {
            return error("检验异常");
        }
    }

    @GetMapping("/getThreeInfo")
    public AjaxResult getThreeInfo(Integer queryId) {
        Map<String, String> threeInfo = spm.getThreeInfo(queryId);
        return success(threeInfo);
    }

}

